﻿//
// *************************************************************************************
// WP-Framework
// 
// Developed by
// Lukas Kretschmar (lkretschmar.dev@bluewin.ch)
//
// Switzerland, Copyright (c) 2013 lkretschmar
// This content is released under the MIT License (http://opensource.org/licenses/MIT).
//     
// *************************************************************************************
//
//

using System;
using KretschIT.WP_Fx.Core.Validation;

namespace KretschIT.WP_Fx.UI.Commands
{
    public class RelayCommand : IRelayCommand
    {
        #region Ctor

        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            It.IsNotNull(() => execute);
            this.execute = execute;
            this.canExecute = canExecute ?? this.DefaultCanExecute;
        }

        #endregion

        #region CanExecute

        private Func<object, bool> DefaultCanExecute
        {
            get { return o => true; }
        }

        public void RaiseCanExecuteChanged()
        {
            if (this.CanExecuteChanged != null)
            {
                this.CanExecuteChanged(this, EventArgs.Empty);
            }
        }
        
        public event EventHandler CanExecuteChanged;

        private Func<object, bool> canExecute;

        public bool CanExecute(object parameter)
        {
            return this.canExecute(parameter);
        }

        #endregion

        #region Execute

        private Action<object> execute;

        public void Execute(object parameter)
        {
            if (this.CanExecute(parameter))
            {
                this.execute(parameter);
            }
        }

        #endregion
    }
}
